from src.game.entity.entity import Entity
from src.math.vector import Vector
from src.helper.movement import MovementHelper
import math

from src.game.entity.fx import EntityFX

class EntityProjectile(Entity):

    name = "entityprojectile"

    def __init__(self):
        Entity.__init__(self)
        self.target = None
        self.vec = None
        self.stop = True
        self.collision = False
        self.width = 0.1
        self.height = 0.1
        self.source = None

    def setTarget(self, x, y):
        self.target = Vector(x, y)

        self.vec = self.target - Vector(self.x, self.y)
        self.vec.normalizeInPlace()


    def update(self):
        Entity.update(self)
        if self.vec is not None:
            if MovementHelper.distanceToPoint((self.x, self.y), self.target) > 0.1:
                self.move(self.vec.x * 1000, self.vec.y * 1000)
            else:
                if self.stop:
                    self.world.despawnEntity(self)
                else:
                    self.move(self.vec.x * 1000, self.vec.y * 1000)

        if self.x < 0 or self.y < 0 or self.x > self.world.parent.width or self.y > self.world.parent.height:
            self.world.despawnEntity(self)


    def readFromPSO(self, pso):
        Entity.readFromPSO(self, pso)
        if pso.get("targetX") is not None and pso.get("targetY") is not None:
            self.target = Vector(pso.get("targetX"), pso.get("targetY"))
        if pso.get("vecX") is not None and pso.get("vecY") is not None:
            self.vec = Vector(pso.get("vecX"), pso.get("vecY"))

    def writeToPSO(self, pso):
        Entity.writeToPSO(self, pso)
        if self.target is not None:
            pso.set("targetX", self.target.x)
            pso.set("targetY", self.target.y)
        if self.vec is not None:
            pso.set("vecX", self.vec.x)
            pso.set("vecY", self.vec.y)

